const express = require("express");
const fs = require("fs");
const path = require("path");

const app = express();

// 中间件函数
function recordMiddleware(req, res, next) {
  let { url, ip } = req;
  fs.appendFileSync(
    path.resolve(__dirname, "./access.log"),
    `${url} ${ip}\r\n`
  );
  next();
}

app.use(recordMiddleware);

app.get("/home", (req, res) => {
  res.send("前台首页");
});

let checkCodeMiddleware = (req, res, next) => {
  if (req.query.code === "521") {
    next();
  } else {
    res.send("暗号错误");
  }
};

app.get("/admin", checkCodeMiddleware, (req, res) => {
  res.send("后台首页");
});

app.get("/setting", checkCodeMiddleware, (req, res) => {
  res.send("后台设置");
});

app.get("*", (req, res) => {
  res.send("404 Not Found");
});

app.listen(3000, () => {
  console.log("服务已经启动，端口 3000 正在监听中....");
});
